<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;
use yii\widgets\ActiveForm;

use app\models\Article;
use app\models\Comment;

/**
 * CommentController implements the CRUD actions for Article model.
 */
class CommentController extends Controller
{
    /**
     * Creates a new Comment model.
     * If creation is successful, the browser will reload the comments list
     * @return mixed
     */
    public function actionCreate()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $comment = new Comment();

        $comment->aid = Yii::$app->request->get('aid');
        if ($comment->load(Yii::$app->request->post()) && $comment->save()) {
            $ret = ['error' => 0, 'aid' => $comment->aid];
        } else {
            $ret = ['error' => 1, 'errmsg' => $comment->getServerValidateErrors()];
        }

        return $ret;
    }

    /**
     * actionCreateValidate
     * 评论的AJAX验证
     *
     * @access public
     * @return void
     */
    public function actionCreateValidate()
    {
        $comment = new Comment();
        Yii::$app->response->format = Response::FORMAT_JSON;
        if (Yii::$app->request->isAjax && $comment->load(Yii::$app->request->post())) {
            return ActiveForm::validate($comment);
        }
    }

    public function actionList()
    {
        $article = Article::findOne(['id' => Yii::$app->request->get('aid')]);
        return $this->renderPartial('list', ['article' => $article]);
    }
}
